<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>mysql | 学习笔记</title><meta name="author" content="lzoxun"><meta name="copyright" content="lzoxun"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="关系型数据库    MySQL、Oracle、SQLServer ….    关系可以理解为，数据库中存在很多报表，表与表之间存在各种关系，通过一个属性，就可以关联出与它有关系的表的某些数据非关系型数据库(Not only SQL)    MongoDB、Redis…..    它相关的数据都可以存在在文档的下级JSON中，不写要太大表与表之间的操作，性能更高 安装官网下载 yum 安装12345">
<meta property="og:type" content="article">
<meta property="og:title" content="mysql">
<meta property="og:url" content="http://example.com/2023/07/22/database/mysql-v2/index.html">
<meta property="og:site_name" content="学习笔记">
<meta property="og:description" content="关系型数据库    MySQL、Oracle、SQLServer ….    关系可以理解为，数据库中存在很多报表，表与表之间存在各种关系，通过一个属性，就可以关联出与它有关系的表的某些数据非关系型数据库(Not only SQL)    MongoDB、Redis…..    它相关的数据都可以存在在文档的下级JSON中，不写要太大表与表之间的操作，性能更高 安装官网下载 yum 安装12345">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png">
<meta property="article:published_time" content="2023-07-22T07:14:09.678Z">
<meta property="article:modified_time" content="2023-07-22T07:14:09.678Z">
<meta property="article:author" content="lzoxun">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="http://example.com/2023/07/22/database/mysql-v2/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"top_n_per_article":1,"unescape":true,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"bottom-left"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'mysql',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-07-22 15:14:09'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const now = new Date()
          const hour = now.getHours()
          const isNight = hour <= 6 || hour >= 18
          if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
          else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>(()=>{
  const $loadingBox = document.getElementById('loading-box')
  const $body = document.body
  const preloader = {
    endLoading: () => {
      $body.style.overflow = ''
      $loadingBox.classList.add('loaded')
    },
    initLoading: () => {
      $body.style.overflow = 'hidden'
      $loadingBox.classList.remove('loaded')
    }
  }

  preloader.initLoading()
  window.addEventListener('load',() => { preloader.endLoading() })

  if (false) {
    document.addEventListener('pjax:send', () => { preloader.initLoading() })
    document.addEventListener('pjax:complete', () => { preloader.endLoading() })
  }
})()</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">108</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">1</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog-info"><a href="/" title="学习笔记"><span class="site-name">学习笔记</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">mysql</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-07-22T07:14:09.678Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-07-22T07:14:09.678Z" title="更新于 2023-07-22 15:14:09">2023-07-22</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="mysql"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p>关系型数据库<br>    MySQL、Oracle、SQLServer ….<br>    关系可以理解为，数据库中存在很多报表，表与表之间存在各种关系，通过一个属性，就可以关联出与它有关系的表的某些数据<br>非关系型数据库(Not only SQL)<br>    MongoDB、Redis…..<br>    它相关的数据都可以存在在文档的下级JSON中，不写要太大表与表之间的操作，性能更高</p>
<h3 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h3><p><a target="_blank" rel="noopener" href="https://www.mysql.com/">官网</a><br><a target="_blank" rel="noopener" href="https://dev.mysql.com/downloads/mysql/">下载</a></p>
<h4 id="yum-安装"><a href="#yum-安装" class="headerlink" title="yum 安装"></a>yum 安装</h4><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">https://blog.csdn.net/weixin_42218986/article/details/125893503</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">下载MySQL安装包 并安装</span></span><br><span class="line">wget https://dev.mysql.com/get/mysql57-community-release-el7-8.noarch.rpm </span><br><span class="line">rpm -ivh mysql57-community-release-el7-8.noarch.rpm</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">跟新秘钥</span></span><br><span class="line">rpm --import https://repo.mysql.com/RPM-GPG-KEY-mysql-2022</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">安装</span></span><br><span class="line">yum install mysql mysql-server mysql-deve # 直接安装</span><br><span class="line">rpm -qi mysql-server # 查看版本</span><br><span class="line">systemctl start mysql # 开启服务</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">登录</span></span><br><span class="line">mysql -u root -p  回车 输入密码登录</span><br><span class="line">mysql -uroot -pxxx 直接输入也可以，u后面空格随意</span><br></pre></td></tr></table></figure>
<h4 id="密码设置"><a href="#密码设置" class="headerlink" title="密码设置"></a>密码设置</h4><blockquote>
<p>规范 包含大小写特殊字符，非连续数字</p>
</blockquote>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">1、方式1</span></span><br><span class="line">mysqladmin -u root password &#x27;lzx123456&#x27; # 第一次设置mysql root密码</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">2、方式2 执行</span></span><br><span class="line">mysql_secure_installation</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">设置不了就获取临时密码</span></span><br><span class="line">grep &#x27;temporary password&#x27; /var/log/mysqld.log</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">降低校验轻度</span></span><br><span class="line">set global validate_password_policy=LOW;</span><br><span class="line">set global validate_password_length=1;</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">如果前面设置密码有限制</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">找到 /etc/my.cnf 最后添加 skip-grant-tables 跳过密码验证（或得到临时密码）</span> </span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">进入mysql 执行命令关闭数据库只读属性</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">1、<span class="built_in">set</span> global read_only=0;</span> </span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">2、flush privileges;</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">3、show variables like <span class="string">&#x27;%read_only%&#x27;</span>;</span> </span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">4、ALTER USER <span class="string">&#x27;root&#x27;</span>@<span class="string">&#x27;localhost&#x27;</span> IDENTIFIED BY <span class="string">&#x27;Lzx542684.@&#x27;</span>;   再次修改密码</span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">后期修改密码</span></span><br><span class="line">1、set global validate_password_policy=0; # 最小限制</span><br><span class="line">2、set global validate_password_length=1; # 密码长度最小值</span><br></pre></td></tr></table></figure>

<p><img src= "" data-lazy-src="/../..%5Cstatic%5Cimg%5C2023-07-05_201917.jpg"></p>
<h4 id="远程授权"><a href="#远程授权" class="headerlink" title="远程授权"></a>远程授权</h4><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">mysql2 conn 都拿不到时</span></span><br><span class="line"></span><br><span class="line">use mysql</span><br><span class="line">update user set host=&#x27;%&#x27; where user=root; # mysql user root 的 localhost 改成 %</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">grant 权限列表 on 数据库 to ‘用户名’@’访问主机’ ;</span></span><br><span class="line">GRANT ALL ON *.* TO &#x27;root&#x27;@&#x27;%&#x27;;</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">通过update语句直接去修改了mysql.user表中的数据的时候，此时我们需要执行flush privileges;命令。</span></span><br><span class="line">FLUSH PRIVILEGES;</span><br></pre></td></tr></table></figure>

<h3 id="基本知识"><a href="#基本知识" class="headerlink" title="基本知识"></a>基本知识</h3><ol>
<li>数据库字符集：默认 <code>utf8mp4</code> ,如果是<code>utf8</code>无法识别<code>emoji</code>表情字符</li>
<li>排序规则：数据库排序操作时，ASC DSC的实现规则</li>
</ol>
<h4 id="表字段的数据类型"><a href="#表字段的数据类型" class="headerlink" title="表字段的数据类型"></a>表字段的数据类型</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">-   数字类型：<span class="string">`TINYINT`</span> <span class="number">1</span> , <span class="string">`SMALLINT`</span> <span class="number">2</span> , <span class="string">`MEDIUMINT`</span> <span class="number">3</span> ，<span class="string">`INT`</span><span class="number">4</span>,<span class="string">`BINGINT`</span><span class="number">8</span></span><br><span class="line">-   浮点数字类型：<span class="string">`FLOAT`</span><span class="number">4</span> , <span class="string">`DOUBLE`</span><span class="number">8</span> , <span class="string">` DECIAML(大小,小数个数)`</span></span><br><span class="line">-   日期类型：</span><br><span class="line">    -   <span class="function"><span class="params">YEAR</span> =&gt;</span> 年 <span class="string">`1901-2155,0000`</span></span><br><span class="line">    -   <span class="function"><span class="params">DATE</span> =&gt;</span> 年月日 <span class="string">`1000-01-01 - 9999-12-31`</span></span><br><span class="line">    -   <span class="string">`DATETIME`</span> =&gt; 年月日 时分秒 <span class="string">`1000-01-01 00:00:00.000000 - 9999-12-31 23:59:59.999999`</span> 支持六位微妙</span><br><span class="line">    -   <span class="string">`TIMESTAMP`</span>  =&gt; 年月日 时分秒 ( 时间访问是<span class="variable constant_">UTC</span>的时间范围 ) <span class="string">`1970-01-01 00:00:00 - 2038-01-19 03:14:07`</span></span><br><span class="line">-   字符串类型：</span><br><span class="line">    -   <span class="variable constant_">CHAR</span>：固定长度，<span class="number">0</span>-<span class="number">255</span></span><br><span class="line">    -   <span class="string">`VAECHAE`</span>：可变长的字符串，长度可以 <span class="number">0</span>-<span class="number">65535</span>直接的值</span><br><span class="line">    -   <span class="variable constant_">BINARY</span>和<span class="variable constant_">VARBINARY</span>：储存二进制字符串</span><br><span class="line">    -   <span class="variable constant_">BLOB</span>：用于储存大的二进制类型</span><br><span class="line">    -   <span class="variable constant_">TEXT</span>：用于储存大的字符串类型</span><br><span class="line">-   ....不常用</span><br></pre></td></tr></table></figure>
<h4 id="表约束"><a href="#表约束" class="headerlink" title="表约束"></a>表约束</h4><blockquote>
<p>  永远不要将<strong>业务的信息字段</strong>作为唯一性主键</p>
</blockquote>
<blockquote>
<p>  每张表为了取反每条记录的<strong>唯一性</strong>，必须有一个<strong>不重复</strong>，<strong>不为空</strong>的字段，设置成主键</p>
</blockquote>
<blockquote>
<p>  多列索引，<strong>联合主键</strong></p>
</blockquote>
 <figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"># 新建表</span><br><span class="line">CREATE TABLE IF NOT EXISTS `students` (  # 如果不存在就创建</span><br><span class="line">    `id` INT PRIMARY KEY AUTO_INCREMENT, # 设置位主键并自动递增</span><br><span class="line">	`name` VARCHAR(10) NOT NULL, # 不能为空</span><br><span class="line">	`norepeat` VARCHAR(10) UNIQUE, # 不能重复</span><br><span class="line">	`age` INT DEFAULT 0 # 最后不能有逗号</span><br><span class="line">)</span><br></pre></td></tr></table></figure>



<h3 id="数据库操作"><a href="#数据库操作" class="headerlink" title="数据库操作"></a>数据库操作</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"># 查看数据库 自带几个默认数据库</span><br><span class="line">show databases;</span><br><span class="line">	infomation_schema =&gt; 储存MySQL在维护的其他按数据库表等信息</span><br><span class="line">	performance_schema =&gt; 性能数据库，记录运行过程中资源消耗相关详细</span><br><span class="line">	mysql =&gt; 储存数据库管理者的用户信息、权限信息以及日志信息等</span><br><span class="line">	sys =&gt; 简易版的 performance_schema</span><br><span class="line">	</span><br><span class="line"># 创建数据库</span><br><span class="line">create database &lt;base-name&gt;;</span><br><span class="line"># 选择使用的数据库</span><br><span class="line">use &lt;base-name&gt;;</span><br><span class="line"># 查看使用的数据库，一切表操作都是基于这个数据库</span><br><span class="line">select database();</span><br><span class="line"># 新建一张表</span><br><span class="line">create table &lt;table-name&gt;(</span><br><span class="line">	name varchar(10),</span><br><span class="line">	age ing);</span><br><span class="line"># 查看表</span><br><span class="line">show tables;</span><br><span class="line"></span><br><span class="line"># 插入数据 到表中</span><br><span class="line">insert into users (name,age) values (&quot;lzo&quot;,18);</span><br><span class="line"># 查询表数据</span><br><span class="line">select * from users; # 查询users表中所有信息</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="SQL语句"><a href="#SQL语句" class="headerlink" title="SQL语句"></a>SQL语句</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">-   <span class="variable constant_">SQL</span>语句操作数据库，常见关系数据库<span class="variable constant_">SQL</span>语句都是比较相似的</span><br><span class="line">-   常见规范</span><br><span class="line">    -   通常大写关键字 如 <span class="variable constant_">CREATE</span></span><br><span class="line">    -   语句以封号结尾</span><br><span class="line">    -   如果关键字作为表名或字段名可以使用引号包裹</span><br></pre></td></tr></table></figure>
<h4 id="DDL-库或表-创建、删除、修改"><a href="#DDL-库或表-创建、删除、修改" class="headerlink" title="DDL 库或表 创建、删除、修改"></a>DDL 库或表 创建、删除、修改</h4><p>DDL 对数据库的操作</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"># DDL 数据定义语句，对数据库或表进行 创建、删除、修改等操作 之 数据库操作</span><br><span class="line"> # 查询所有数据库</span><br><span class="line"> SHOW DATABASES;</span><br><span class="line"> </span><br><span class="line"> # 选择数据库</span><br><span class="line"> USE lzoxun;</span><br><span class="line"> </span><br><span class="line"> # 查看当前正在使用的数据库</span><br><span class="line"> SELECT DATABASE();</span><br><span class="line"> </span><br><span class="line"> # 创建新数据库</span><br><span class="line"> # CREATE DATABASE users; # 直接创建</span><br><span class="line"> CREATE DATABASE IF NOT EXISTS users; # 如果不存在就创建</span><br><span class="line"> </span><br><span class="line"> # 删除数据库</span><br><span class="line"> DROP DATABASE IF EXISTS users; # 如果存在就删除</span><br><span class="line"> </span><br><span class="line"> # 修改数据库 (字符集和排序规则,一般右键数据库直接改)</span><br><span class="line"> ALTER DATABASE users  CHARACTER SET = utf8 COLLATE = utf8_unicode_ci;</span><br></pre></td></tr></table></figure>



<p>DDL 对表的操作</p>
   <figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"># DDL 数据定义语句，对数据库或表进行 创建、删除、修改等操作 之 表的操作</span><br><span class="line"></span><br><span class="line"># 查看所有表</span><br><span class="line">SHOW TABLES;</span><br><span class="line"></span><br><span class="line"># 新建表</span><br><span class="line">CREATE TABLE IF NOT EXISTS `students` (  # 如果不存在就创建</span><br><span class="line">  `id` INT PRIMARY KEY AUTO_INCREMENT, # 设置位主键并自动递增</span><br><span class="line">	`name` VARCHAR(10) NOT NULL, # 不能为空</span><br><span class="line">	`norepeat` VARCHAR(10) UNIQUE, # 不能重复</span><br><span class="line">	`age` INT DEFAULT 0 # 最后不能有逗号</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"># 修改表名字</span><br><span class="line">ALTER TABLE `students2` RENAME TO `students`;</span><br><span class="line"></span><br><span class="line"># 添加新的列</span><br><span class="line">ALTER TABLE `students` ADD `updateTime` TIMESTAMP;</span><br><span class="line"></span><br><span class="line"># 修改字段名称</span><br><span class="line">ALTER TABLE `students` CHANGE `updateTime` `createTime` TIMESTAMP; </span><br><span class="line"></span><br><span class="line"># 修改字段类型</span><br><span class="line">ALTER TABLE `students` MODIFY `name` VARCHAR(30);</span><br><span class="line">ALTER TABLE `students` MODIFY `createTime` TIMESTAMP DEFAULT CURRENT_TIMESTAMP; # 默认创建时间 CURRENT_TIMESTAMP 与 字段类型匹配</span><br><span class="line">ALTER TABLE `students` MODIFY `updateTime` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP; # 默认值为更新时候的时间 </span><br><span class="line"></span><br><span class="line"># 删除一个字段</span><br><span class="line">ALTER TABLE `students` DROP `age`;</span><br><span class="line"></span><br><span class="line"># 查看表结构</span><br><span class="line">DESC `students`;</span><br><span class="line"></span><br><span class="line"># 根据表结构创建新表</span><br><span class="line">CREATE TABLE `copytable2` LIKE `students`;</span><br><span class="line"></span><br><span class="line"># 根据表结构和内容创建新表(包括内容一起创建)</span><br><span class="line">CREATE TABLE `copytable3` (SELECT * FROM `students`);</span><br><span class="line"></span><br><span class="line"># 查看创建表时使用的语句</span><br><span class="line">SHOW CREATE TABLE `students`; </span><br><span class="line"></span><br><span class="line"># 删除表</span><br><span class="line">DROP TABLE IF EXISTS `students`; # 如果存在就删除</span><br></pre></td></tr></table></figure>

<h4 id="DML-数据-添加、删除、修改"><a href="#DML-数据-添加、删除、修改" class="headerlink" title="DML 数据 添加、删除、修改"></a>DML 数据 添加、删除、修改</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"># DML 对表数据进行 添加、删除、修改等操作</span><br><span class="line"></span><br><span class="line"># 插入数据</span><br><span class="line"># INSERT INTO `students` VALUES (110,&quot;liao&quot;,&#x27;1444&#x27;,&#x27;2022-10-10 12:33:00&#x27;);  # 全表</span><br><span class="line">INSERT INTO `students` (name,norepeat) VALUES (&quot;liao2&quot;,&quot;144453d1&quot;); #插入指定数据 </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># 删除数据</span><br><span class="line">DELETE FROM `students`; # 删除所有数据</span><br><span class="line">DELETE FROM `students` WHERE id = 1;# 删除表中符合条件的数据</span><br><span class="line"></span><br><span class="line"># 更新数据</span><br><span class="line">UPDATE `students` SET name = &#x27;大都是&#x27;, norepeat = &#x27;4589&#x27; WHERE id = 111; # 更新符合条件的数据</span><br></pre></td></tr></table></figure>

<h4 id="DQL-数据-查询"><a href="#DQL-数据-查询" class="headerlink" title="DQL 数据 查询"></a>DQL 数据 查询</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"># DQL 从数据库中查询记录</span><br><span class="line"></span><br><span class="line"># 普通查询</span><br><span class="line">SELECT * FROM `students`; # 查询所有数据与字段</span><br><span class="line">SELECT name,norepeat FROM `students`; # 查询指定字段</span><br><span class="line">SELECT name as listName,norepeat FROM `students`; # 查询指定字段并起别名</span><br><span class="line"></span><br><span class="line"># 条件判断查询</span><br><span class="line">SELECT * FROM `students` WHERE `norepeat` &gt;= 5; # 查询 norepeat &gt;= 、= 、!=、&lt;&gt; 5 的记录</span><br><span class="line"></span><br><span class="line"># 逻辑运算语句</span><br><span class="line">SELECT * FROM `students` WHERE `norepeat` &gt;= 5 AND `name` = &#x27;liao8&#x27;; # 查询 大于5 并且 name 为liao8 的数据</span><br><span class="line">SELECT * FROM `students` WHERE `norepeat` &gt;= 5 &amp;&amp; `norepeat` != 8; # 查询 大于5 并且 不等于8 的记录</span><br><span class="line">SELECT * FROM `students` WHERE `norepeat` BETWEEN 5 AND 8; # 查询 5-8 的记录</span><br><span class="line"></span><br><span class="line">SELECT * FROM `students` WHERE `norepeat` &gt;= 5 OR `name` = &#x27;liao1&#x27;; # 查询 大于5 或者 name 为liao1 的数据 ( || )</span><br><span class="line">SELECT * FROM `students` WHERE `norepeat` IS NULL; # 查询 norepeat 为 null 的记录</span><br><span class="line"> </span><br><span class="line"># 模糊查询</span><br><span class="line">SELECT * FROM `students` WHERE `name` LIKE &quot;%8%&quot;; # % 表示任意个任意字符，只要 name 存在 8，就可以查出来</span><br><span class="line">SELECT * FROM `students` WHERE `name` LIKE &quot;__ao8&quot;; # _ 表示一个任意字符</span><br><span class="line"></span><br><span class="line"># 在列表中的，全都查</span><br><span class="line">SELECT * FROM `students` WHERE `name` IN (&#x27;liao1&#x27;,&#x27;liao2&#x27;,&#x27;liao3&#x27;);</span><br><span class="line"></span><br><span class="line"># 对查询结果排序</span><br><span class="line">SELECT * FROM `students` WHERE `name` LIKE &quot;liao_&quot; ORDER BY norepeat DESC, id ASC; # 将查到的记录通过 norepeat 字段进行降序,再同 id 升序</span><br><span class="line"></span><br><span class="line"># 分页查询</span><br><span class="line">SELECT * FROM students LIMIT 2 OFFSET 0; # 查询 2 条，偏移 0 ((pageSize-1)*pageNumber) 条 , 第一页，查出1-2条记录</span><br><span class="line">SELECT * FROM students LIMIT 2 OFFSET 2; # 查询 2 条，偏移 2 ((pageSize-1)*pageNumber) 条 , 第二页，查出3-4条件记录</span><br><span class="line">SELECT * FROM students LIMIT 2,2; # 也行</span><br><span class="line"></span><br><span class="line"># ============================================================</span><br><span class="line"># 聚合操作 </span><br><span class="line">SELECT SUM(norepeat) FROM `students`; # 对 int 类型列进行求和</span><br><span class="line">SELECT SUM(norepeat) FROM `students` WHERE id &gt; 124; # di 大于 124 的记录的norepeat 进行求和</span><br><span class="line">SELECT AVG(norepeat) FROM `students`; # 求平均值 MAX() 最大值、MIN() 最小值、COUNT(*)  统计记录个数，</span><br><span class="line">SELECT COUNT(DISTINCT norepeat) FROM `students`; # 统计个数并去重</span><br><span class="line"></span><br><span class="line"># 分组 </span><br><span class="line"># 因为 GROUP BY `group` 所以SELECT 后面可以加 group, 不然不能这么加的</span><br><span class="line">SELECT `group`,AVG(norepeat),COUNT(*) FROM `students` GROUP BY `group`; # 用group分组，计算出每个种类数据，norepleat 的平均值，与记录个数</span><br><span class="line"></span><br><span class="line"># HAVING 作用于组, 和 WHERE作用类似，但是它是在分组后进行过滤的</span><br><span class="line">SELECT `group`,AVG(norepeat),COUNT(*) count FROM `students` GROUP BY `group` HAVING count = 2; </span><br><span class="line"></span><br><span class="line"># 通过 WHERE 过滤完再进行分组, WHERE 作用于表</span><br><span class="line">SELECT `group`,AVG(norepeat),COUNT(*) count FROM `students` WHERE id &gt; 121 GROUP BY `group`; </span><br><span class="line"></span><br><span class="line"># 多表查询</span><br><span class="line"># 主表中有时候，相同类型或组， 数据是很多的，当想给类型，添加额外属性，就需要利用新表，否则，主表每个相同类型都有相同的新属性，难以维护 </span><br></pre></td></tr></table></figure>


<h4 id="DCL-库和表的权限操作"><a href="#DCL-库和表的权限操作" class="headerlink" title="DCL 库和表的权限操作"></a>DCL 库和表的权限操作</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"># 数据控制语言，对数据库和表的权限进行相关访问控制操作</span><br></pre></td></tr></table></figure>



<h3 id="主键外键多表操作"><a href="#主键外键多表操作" class="headerlink" title="主键外键多表操作"></a>主键外键多表操作</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line">CREATE TABLE IF NOT EXISTS `brand` (</span><br><span class="line">	id INT PRIMARY KEY AUTO_INCREMENT,</span><br><span class="line">	name VARCHAR(20) NOT NULL,</span><br><span class="line">	website VARCHAR(100),</span><br><span class="line">	phoneRank INT</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line">INSERT INTO `brand` (name,website,phoneRank) VALUES (&#x27;华为&#x27;,&#x27;www.huawei.com&#x27;,2);</span><br><span class="line">INSERT INTO `brand` (name,website,phoneRank) VALUES (&#x27;联想&#x27;,&#x27;www.lianxiang.com&#x27;,4);</span><br><span class="line">INSERT INTO `brand` (name,website,phoneRank) VALUES (&#x27;戴尔&#x27;,&#x27;www.daier.com&#x27;,3);</span><br><span class="line">INSERT INTO `brand` (name,website,phoneRank) VALUES (&#x27;苹果&#x27;,&#x27;www.pingguo.com&#x27;,10);</span><br><span class="line">INSERT INTO `brand` (name,website,phoneRank) VALUES (&#x27;小米&#x27;,&#x27;www.xiaomi.com&#x27;,5);</span><br><span class="line">INSERT INTO `brand` (name,website,phoneRank) VALUES (&#x27;oppo&#x27;,&#x27;www.oppo.com&#x27;,8);</span><br><span class="line">INSERT INTO `brand` (name,website,phoneRank) VALUES (&#x27;京东&#x27;,&#x27;www.jingdong.com&#x27;,7);</span><br><span class="line">INSERT INTO `brand` (name,website,phoneRank) VALUES (&#x27;谷歌&#x27;,&#x27;www.google.com&#x27;,9);</span><br><span class="line"></span><br><span class="line">CREATE TABLE IF NOT EXISTS `products` (</span><br><span class="line">	id INT PRIMARY KEY AUTO_INCREMENT,</span><br><span class="line">	brand VARCHAR(20),</span><br><span class="line">	title VARCHAR(100),</span><br><span class="line">	price FLOAT,</span><br><span class="line">	url VARCHAR(100),</span><br><span class="line">	score FLOAT</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line">INSERT INTO `products` (brand,price,url,title,score) VALUES (&#x27;华为&#x27;,6666,&#x27;www.xxxxx.com&#x27;,&#x27;华为 nova 2&#x27;,8.5); # 添加数据</span><br><span class="line">INSERT INTO `products` (brand,price,url,title,score) VALUES (&#x27;华为&#x27;,7777,&#x27;www.xxxxx.com&#x27;,&#x27;华为 nova 3&#x27;,9.);</span><br><span class="line"></span><br><span class="line"># 给 products 添加 brand 的外键</span><br><span class="line">ALTER TABLE `products` ADD `brand_id` INT;</span><br><span class="line">ALTER TABLE `products` ADD FOREIGN KEY(brand_id) REFERENCES brand(id); # 设置成外键，并添加外键约束 （brand_id 必须是 brand表中存在的id）</span><br><span class="line"></span><br><span class="line"># 设置brand_id</span><br><span class="line">UPDATE `products` SET `brand_id` = 1 WHERE `brand` = &#x27;华为&#x27;; # 因为 brand 中华为的id就是1</span><br><span class="line">UPDATE `products` SET `brand_id` = 5 WHERE `brand` = &#x27;oppo&#x27;;</span><br><span class="line">UPDATE `products` SET `brand_id` = 4 WHERE `brand` = &#x27;小米&#x27;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># 修改和删除被当做外键引用了的id (id 默认不能修改)</span><br><span class="line"># 从工具中表右键 - 设计表 - 外键 有一个删除时的值 RESTRICT ，更新时的值 RESTRICT，界面可以直接修改状态</span><br><span class="line"># 将它们的值 从RESTRICT 该为 CASCADE ，如果id改了，子集引用了这个id的外键会自动更新</span><br><span class="line"># 将它们的值 从RESTRICT 该为 SET NULL ，如果id改了，子集引用了这个id的外键会自动变 NULL</span><br><span class="line"></span><br><span class="line"># SQL 语句修改</span><br><span class="line">SHOW CREATE TABLE `products`; # 查看外键的表 的 创建表的语句，哪里有外键关联信息</span><br><span class="line">ALTER TABLE `products` DROP FOREIGN KEY products_ibfk_1; # 根据名称删除外键</span><br><span class="line"># 重新关联外键，并指定更新时的值为 CASCADE 删除时的默认(如果删除也设置成 CASCADE 那么，父一删除，关联它的id外键也会全部删除)</span><br><span class="line">ALTER TABLE `products` ADD FOREIGN KEY (brand_id) REFERENCES brand(id) ON UPDATE CASCADE ON DELETE RESTORE;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="多表联合查询"><a href="#多表联合查询" class="headerlink" title="多表联合查询"></a>多表联合查询</h4><blockquote>
<p>  SQL JOIN</p>
</blockquote>
<ul>
<li>左连接</li>
<li>有连接</li>
<li>内连接</li>
<li>全连接</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"># 多表设计查询 - 多表查询 SQL JOIN</span><br><span class="line"># 1、左连接，查询表 products 和 brand 的数据，通过products.brand_id 和 brand.id 进行关联;</span><br><span class="line"></span><br><span class="line"># 作用 以左表为主，查询出 pruducts 所有数据，在把右表中 id 等于 左表 brand_id 的记录，追加到对应记录后面，</span><br><span class="line">SELECT * FROM `products` LEFT JOIN `brand` ON products.brand_id = brand.id;</span><br><span class="line"></span><br><span class="line"># 作用 以左表为主，查询出 pruducts 所有数据，在把右表中 id 等于 左表 brand_id 的记录删除，只留下左表独有的数据</span><br><span class="line">SELECT * FROM `products` LEFT JOIN `brand` ON products.brand_id = brand.id WHERE brand.id IS NULL;</span><br><span class="line"></span><br><span class="line">#=================</span><br><span class="line"># 2、右连接，查询表 products 和 brand 的数据，通过products.brand_id 和 brand.id 进行关联;</span><br><span class="line"></span><br><span class="line"># 作用 以右表为主，查询出 brand 所有数据，在左表中 brand_id 等于 右表 id 的记录，追加到对应记录前面</span><br><span class="line">SELECT * FROM `products` RIGHT JOIN `brand` ON products.brand_id = brand.id;</span><br><span class="line"></span><br><span class="line"># 作用 以右表为主，查询出 brand 所有数据，在左表中 brand_id 等于 右表 id 的记录删除，只留下右边表独有的数据</span><br><span class="line">SELECT * FROM `products` RIGHT JOIN `brand` ON products.brand_id = brand.id WHERE products.brand_id IS NULL;</span><br><span class="line"></span><br><span class="line">#=================</span><br><span class="line"># 3、内连接 查找products.brand_id 能关联上 brand.id , brand.id 也能关联上 products.brand_id 的记录</span><br><span class="line"></span><br><span class="line">SELECT * FROM `products` JOIN `brand` ON products.brand_id = brand.id;</span><br><span class="line"></span><br><span class="line">#=================</span><br><span class="line"># 4、全连接 （左连接 + 有连接 + 删除重复）</span><br><span class="line">(SELECT * FROM `products` LEFT JOIN `brand` ON products.brand_id = brand.id)</span><br><span class="line">UNION</span><br><span class="line">(SELECT * FROM `products` RIGHT JOIN `brand` ON products.brand_id = brand.id);</span><br><span class="line"> </span><br><span class="line"># 去交集 只要左边关联不到右边，右边也关联不到左边的数据</span><br><span class="line">(SELECT * FROM `products` LEFT JOIN `brand` ON products.brand_id = brand.id WHERE brand.id IS NULL)</span><br><span class="line">UNION</span><br><span class="line">(SELECT * FROM `products` RIGHT JOIN `brand` ON products.brand_id = brand.id WHERE products.brand_id IS NULL);</span><br></pre></td></tr></table></figure>

<h4 id="多对多关系"><a href="#多对多关系" class="headerlink" title="多对多关系"></a>多对多关系</h4><blockquote>
<p>lzoxun 下查询文件</p>
</blockquote>
<h3 id="扩展知识"><a href="#扩展知识" class="headerlink" title="扩展知识"></a>扩展知识</h3><h4 id="ORM"><a href="#ORM" class="headerlink" title="ORM"></a>ORM</h4><blockquote>
<p>  **对象映射关系 ** <code>ORM</code> 是一种程序设计方案</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">-   效果上，他提供了一个可在变成语言中 使用虚拟对象数据库的效果</span><br><span class="line"></span><br><span class="line">-   <span class="title class_">Node</span> 常用的：<span class="string">`sequelize`</span> ...</span><br><span class="line"></span><br><span class="line">    -   <span class="string">`npm install mysql2 sequelize --save`</span></span><br><span class="line"></span><br><span class="line">-   <span class="variable constant_">JAVA</span> 经常使用的<span class="variable constant_">ORM</span>包括：<span class="string">`Hibernate`</span>、<span class="string">`MyBatis`</span>、...  </span><br><span class="line"></span><br><span class="line">    -   不使用<span class="variable constant_">ORM</span>的操作方式</span><br><span class="line">        -    node项目中编写sql语句，传到数据库处理，返回得到的结果到 node项目</span><br><span class="line"></span><br><span class="line">    -   使用<span class="variable constant_">ORM</span>的操作方式</span><br><span class="line">        -    不用变形<span class="variable constant_">SQL</span>语句，操作<span class="variable constant_">ORM</span>库提供的 类 的 方法</span><br><span class="line">        -   <span class="variable constant_">ORM</span>库会将你的操作转换成 <span class="variable constant_">SQL</span>语句，传到数据库处理，返回得到的结果到<span class="variable constant_">ORM</span>，再经过处理返回给用户</span><br></pre></td></tr></table></figure>
<h4 id="GUR工具"><a href="#GUR工具" class="headerlink" title="GUR工具"></a>GUR工具</h4><p><a target="_blank" rel="noopener" href="http://www.navicat.com.cn/download/direct-download?product=navicat_premium_cs_x64.exe&location=1">Navicat</a></p>
<p>设置查询文件位置：数据库右键编辑 - 高级 - 位置设置</p>
<p>数据库连接</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 连接云服务器，需要先开放 3306 端口，在 将服务器mysql数据库中，要连接的用户root的host该为% (默认值是localhost 限制只有本地才能连接)</span></span><br><span class="line"><span class="comment"> * use mysql</span></span><br><span class="line"><span class="comment"> * update user set host = &#x27;%&#x27; where user = &#x27;root&#x27;;</span></span><br><span class="line"><span class="comment"> * 成功后重启mysql</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> */</span></span><br></pre></td></tr></table></figure>
<p>数据的导出与导入<br>1、导出的服务器 右键数据库 -&gt; 转储 SQL 文件到本地 -&gt; 生成一个 数据库名.sql 的文件<br>2、导入的服务器 右键运行 SQL 文件 -&gt; 选择刚刚导出的 sql 文件 -&gt; 开始，</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">工具快捷键</span><br><span class="line">-   <span class="string">`Ctrl + q`</span>：打开查询界面</span><br><span class="line">-   <span class="string">`Ctrl + r`</span>：运行当前查询界面的sql语句</span><br><span class="line">-   <span class="string">`Ctrl + Shift + r`</span>：运行焦点所在的sql语句</span><br><span class="line">-   <span class="string">`Ctrl + d`</span>：复制当前行</span><br><span class="line">-   <span class="string">`Ctrl + l`</span>：历史日志</span><br><span class="line">-   <span class="string">`F6`</span>：命令行界面</span><br></pre></td></tr></table></figure>


<p>MySql报错only_full_group_by<br>    5.7 以上使用 JSON_ARRAYAGG 就必须 GROUP BY分组，mysql2 有限制，有些sql外面工具可以不发分</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://example.com">lzoxun</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://example.com/2023/07/22/database/mysql-v2/">http://example.com/2023/07/22/database/mysql-v2/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://example.com" target="_blank">学习笔记</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2023/07/22/echarts/" title=""><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info"></div></div></a></div><div class="next-post pull-right"><a href="/2023/07/22/idea/idea-vscode/" title="VsCode 编辑器"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">VsCode 编辑器</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">lzoxun</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">108</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">1</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/liaozhongxun"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/liaozhongxun" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a><a class="social-icon" href="mailto:869664233@gmail.com" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">这是我的文档</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%89%E8%A3%85"><span class="toc-number">1.</span> <span class="toc-text">安装</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#yum-%E5%AE%89%E8%A3%85"><span class="toc-number">1.1.</span> <span class="toc-text">yum 安装</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AF%86%E7%A0%81%E8%AE%BE%E7%BD%AE"><span class="toc-number">1.2.</span> <span class="toc-text">密码设置</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%BF%9C%E7%A8%8B%E6%8E%88%E6%9D%83"><span class="toc-number">1.3.</span> <span class="toc-text">远程授权</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E7%9F%A5%E8%AF%86"><span class="toc-number">2.</span> <span class="toc-text">基本知识</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%A1%A8%E5%AD%97%E6%AE%B5%E7%9A%84%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B"><span class="toc-number">2.1.</span> <span class="toc-text">表字段的数据类型</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%A1%A8%E7%BA%A6%E6%9D%9F"><span class="toc-number">2.2.</span> <span class="toc-text">表约束</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%95%B0%E6%8D%AE%E5%BA%93%E6%93%8D%E4%BD%9C"><span class="toc-number">3.</span> <span class="toc-text">数据库操作</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#SQL%E8%AF%AD%E5%8F%A5"><span class="toc-number">4.</span> <span class="toc-text">SQL语句</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#DDL-%E5%BA%93%E6%88%96%E8%A1%A8-%E5%88%9B%E5%BB%BA%E3%80%81%E5%88%A0%E9%99%A4%E3%80%81%E4%BF%AE%E6%94%B9"><span class="toc-number">4.1.</span> <span class="toc-text">DDL 库或表 创建、删除、修改</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#DML-%E6%95%B0%E6%8D%AE-%E6%B7%BB%E5%8A%A0%E3%80%81%E5%88%A0%E9%99%A4%E3%80%81%E4%BF%AE%E6%94%B9"><span class="toc-number">4.2.</span> <span class="toc-text">DML 数据 添加、删除、修改</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#DQL-%E6%95%B0%E6%8D%AE-%E6%9F%A5%E8%AF%A2"><span class="toc-number">4.3.</span> <span class="toc-text">DQL 数据 查询</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#DCL-%E5%BA%93%E5%92%8C%E8%A1%A8%E7%9A%84%E6%9D%83%E9%99%90%E6%93%8D%E4%BD%9C"><span class="toc-number">4.4.</span> <span class="toc-text">DCL 库和表的权限操作</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BB%E9%94%AE%E5%A4%96%E9%94%AE%E5%A4%9A%E8%A1%A8%E6%93%8D%E4%BD%9C"><span class="toc-number">5.</span> <span class="toc-text">主键外键多表操作</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%A4%9A%E8%A1%A8%E8%81%94%E5%90%88%E6%9F%A5%E8%AF%A2"><span class="toc-number">5.1.</span> <span class="toc-text">多表联合查询</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%A4%9A%E5%AF%B9%E5%A4%9A%E5%85%B3%E7%B3%BB"><span class="toc-number">5.2.</span> <span class="toc-text">多对多关系</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%89%A9%E5%B1%95%E7%9F%A5%E8%AF%86"><span class="toc-number">6.</span> <span class="toc-text">扩展知识</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#ORM"><span class="toc-number">6.1.</span> <span class="toc-text">ORM</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#GUR%E5%B7%A5%E5%85%B7"><span class="toc-number">6.2.</span> <span class="toc-text">GUR工具</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/window/win-11/" title="win 11 set">win 11 set</a><time datetime="2023-07-22T07:14:09.700Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/window/win-gitbash/" title="git bash">git bash</a><time datetime="2023-07-22T07:14:09.700Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/window/win-wsl/" title="wsl">wsl</a><time datetime="2023-07-22T07:14:09.700Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/window/win-main/" title="window">window</a><time datetime="2023-07-22T07:14:09.700Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/web/%E5%85%BC%E5%AE%B9%E9%97%AE%E9%A2%98/" title="兼容问题">兼容问题</a><time datetime="2023-07-22T07:14:09.699Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By lzoxun</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdn.jsdelivr.net/npm/pangu/dist/browser/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (false){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><div class="js-pjax"></div><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-nest.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div class="no-result" id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/haruto.model.json"},"display":{"position":"right","width":100,"height":200,"right":300},"mobile":{"show":true}});</script></body></html>